/**
 * 职员账号管理中的职位管理
 */
import React, {Component} from "react";
import "antd/dist/antd.css";
import "../css/positionManage.css";
import {admin, menu, role} from "../value";
import app from "../app";
import {
    Button,
    Col,
    Form,
    Input,
    Icon,
    Layout,
    Modal,
    Row,
    Table,
    Tree
} from "antd";
import reqwest from "reqwest";
import {AddPositions, EditPositions} from '../components/operateManage';

const {Content} = Layout;
const confirm = Modal.confirm;
let pageLength = app.pageLength;
const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
//根据最顶层的数据所含的子数据的ID和所有的分类ID比较，相同的则为他的子数据  循环权限
const loop = (menu, data) => {
    let menuList = [];
    data.map((item, index) => {
        if (menu.menu_id === item.menu_parentid) {
            menuList.push(item);
            menu.subList = menuList;
            loop(item, data);
        } else {
            menuList = [];
        }
    })
};

class PositionManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAddValid: false,  //是否弹出发布优惠券的框
            data: [],  //表格中的数据
            pagination: {total: 0, current: 0, pageSize: 0},
            loading: false,
            menuList: [],  //查找的所有权限,传给子组件。生成树
            roleList: [], //所有的职位
            menu_id: [],  //选中的所有菜单ID
            occurMenuList: [],  //复选框选中的菜单
            addConfirmLoading: false, //添加框中的确定loading样式
            editConfirmLoading: false,//编辑框中的确定loading样式
            positionId: [],  //批量选中的所有的职位ID
            positionName: [],//批量选中的所有的职位名称
            typeHelp: '',  //控制分类权限的出错文字
            selectCount: 0,  //已选择多少项
            currentPageSize: 0//当前页面数据条数

        };
    }

    columns = [
        {
            title: '角色名',
            dataIndex: 'role_name',
        },
        {
            title: '职位类型',
            dataIndex: 'role_type',
            render: role_type => {
                let text = '';
                if (role_type == '1') {
                    text = '管理员';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '是否有效',
            dataIndex: 'role_isable',
            render: role_isable => {
                let text = '';
                if (role_isable == '1') {
                    text = '有效';
                } else {
                    text = '无效';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (<div>
                    <EditPositions/>
                    <Button style={{marginLeft: 10}} type="danger" onClick={() => {
                        this.handleDelete(data.role_id, data.role_name)
                    }}>删除</Button>
                </div>)
            }

        }
    ];

    render() {
        const {getFieldDecorator} = this.props.form;
        const {pagination, currentPageSize} = this.state;
        const rowSelection = {
            // 表格中复选框发生变化时
            onChange: (selectedRowKeys, selectedRows) => {
                let positionId = [];
                let positionName = [];
                positionId = selectedRowKeys;
                selectedRows.forEach((item) => {
                    positionName.push(item.role_name);
                });
                this.setState({
                    positionId: positionId,  //批量选中的职位ID
                    positionName: positionName,
                    selectCount: selectedRowKeys.length, //一共选择的职位数量
                })
            },

        };
        return (
            <span>
                <Row>
                    <Col className='titleSize btnBottom'>职位管理</Col>
                    <div style={{marginBottom: '15px', marginTop: 10}}>
                          <AddPositions
                              addConfirmLoading={this.state.addConfirmLoading}
                              isVisible={this.state.isAddValid = null ? false : this.state.isAddValid}
                              title={'增加职位'}
                              buttonText={'增加职位'}
                              width={'600px'}
                              newKey={'0'}
                              clickOk={(e) => this.handleSubmit(e)}   //点击添加框的确定
                              clickCancel={(e) => this.handleCancel(false)}   //关闭添加框的取消
                              click={(e) => this.handleCancel(true)}       // 弹出添加框
                          >
                        </AddPositions>

                        <Button type="danger" style={{marginLeft: '10px'}} onClick={() => {
                            this.handleDeleteAll()
                        }}>批量删除</Button>
                    </div>
                      <div className="selectCount">
                          <Icon style={{color: '#0391f5', margin: '0px 10px'}} type="info-circle"/>
                          <span>已选择{this.state.selectCount}项</span>
                      </div>
                    <div style={{fontSize: 12, marginBottom: 20}}>
                        当前第<span style={{color: 'red'}}>{pagination.current}</span>页, 当前页共<span
                        style={{color: 'red'}}>{currentPageSize}</span>条数据，一共<span
                        style={{color: 'red'}}>{pagination.total}</span>条数据
                    </div>
                    <Table
                        rowSelection={rowSelection}
                        columns={this.columns}
                        rowKey={record => record.role_id}
                        dataSource={this.state.data}
                        pagination={this.state.pagination}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                    />
                </Row>
            </span>
        );
    }

    componentDidMount() {
        const param = {page: 1, size: 10, role_type: '1'};
        this.searchRoleList(param);
        //this.searchRole();
    }

    // 改变吗，每页显示多少条数据
    changePageSize(value) {
        this.state.pagination.current = 0;
        pageLength = parseInt(value);
        this.fetch();
    }

    // 所有的菜单权限
    searchRole() {
        let roleId = app.getData('role_id');
        // 防止有些商家没有权限
        if (roleId) {
            app.post(menu.SEARCH_MENU_BY_ROLEID, {
                role_id: roleId
            }).then(req => {
                if (req.code == 1) {
                    console.log(req.data);
                    let firstMenu = [];
                    req.data.map((item) => {
                        if (item.menu_level === 1) {
                            firstMenu.push(item);
                        }
                    });
                    firstMenu.map((item) => {
                        loop(item, req.data);
                    });
                    console.log(firstMenu);
                    this.setState({menuList: firstMenu});
                } else if (req.code == 4) {
                    app.alert(req.error, 'error', 3);
                } else {
                    app.alert(req.msg, 'error', 3);
                }
                this.setState({loading: false});
            })
        }
    }

    isEmptyObject(filters) {
        for (let key in filters) {
            if (key) {
                this.setState({param: filters});
                return filters;
            }
        }
        return null;
    }

    // 获取编辑子组件的值  主要是编辑框确定之后刷新表格
    handleEditSubmit() {
        let _this = this;
        this.fetch({
            startList: _this.state.pagination.current,
            ..._this.state.param
        })
    }

    // 获取分类子组件中的值
    getTypeId(select, value) {
        this.setState({
            roleList: select,  //key值
            menu_id: value,
            typeHelp: '',
            occurMenuList: select
        })
    }

    // 分页、排序、筛选变化时触发
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.searchAdminList({page: current, size});
    };

    /**
     * 查找角色列表
     * @param params
     */
    searchRoleList = (param = {}) => {
        let _this = this;
        param.role_type='1';
        _this.setState({loading: true});
        app.post(role.SEARCH_ROLE_LIST, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                const pagination = {total: result.count, current: param.page, pageSize: param.size};
                this.setState({pagination, data: data, loading: false});
            } else {
                app.alert(result.msg, 'info', 1);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false});
            }
        });
    };

    // 请求删除数据
    requestDelete(roleId, roleName, type) {
        let _this = this;
        confirm(
            {
                content: '您确定要删除此职位吗？',
                onOk() {
                    app.post(menu.DEL_ROLE, {
                        token: app.getToken(),
                        role_id: roleId,
                        role_name: roleName
                    }).then(req => {
                        if (req.code == 1) {
                            let length = _this.state.data.length;
                            let current = _this.state.pagination.current;
                            // 批量删除
                            if (type === 'all') {
                                if (current > 0) {
                                    current--;
                                }
                            } else {
                                if (length == 1) {
                                    current--;
                                }
                            }
                            _this.setState({
                                positionId: [],  //批量选中的所有的职位ID
                                positionName: [],//批量选中的所有的职位名称
                                pagination: {current: current}
                            });
                            app.alert('删除成功', 'success', 3);
                            _this.fetch({
                                startList: current,
                            });
                        } else {
                            app.alert(req.msg, 'error', 3);
                        }
                    })
                },
                onCancel() {
                },
            });
    }

    // 单个删除
    handleDelete(id, name) {
        this.requestDelete(id, name);
    }

    // 批量删除
    handleDeleteAll() {
        let listId = '';
        let listName = '';
        if (this.state.positionId == '') {
            app.alert('请选择要删除的职位', 'error', 3);
        } else {
            this.state.positionId.map((item) => {
                listId += item + ',';
            });

            this.state.positionName.map((item) => {
                listName += item + ',';
            })

            listId = listId.substring(0, listId.length - 1); //删除最后一个逗号
            listName = listName.substring(0, listName.length - 1);
            this.requestDelete(listId, listName, 'all');
        }
    }

    //添加的确定按钮
    handleSubmit = (e) => {
        let that = this;
        let menuId = '';
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.state.menu_id == '') {
                    this.setState({
                        typeHelp: '请选择权限'
                    })
                } else {
                    let typeId = this.state.menu_id;  //选中的权限的ID
                    typeId.forEach((item) => {
                        menuId += item + ',';
                    });
                    menuId = menuId.substring(0, menuId.length - 1);
                    values.menu_id = menuId;
                    values.role_type = '2';
                    this.setState({loading: true, addConfirmLoading: true});
                    app.post(menu.ADD_ROLE, values).then(req => {
                        this.setState({loading: false, addConfirmLoading: false});
                        if (req.code == 1) {
                            this.setState({isAddValid: false, occurMenuList: [], menu_id: []});
                            this.props.form.resetFields();  //添加成功后清空表单
                            this.fetch({startList: this.state.pagination.current});
                            app.alert('添加成功', 'success', 3);
                        } else {
                            app.alert(req.msg, 'error', 3);
                        }

                    })
                }
            }
        });
    }

    // 弹出或者关闭
    handleCancel(isValid) {
        this.props.form.resetFields();
        this.setState({
            isAddValid: isValid,
            occurMenuList: []
        })
    }

//刷新当前页面
    handleRefresh = () => {
        this.fetch({
            startList: this.state.pagination.current,
            ...this.state.param,
        });
    }

}

// 树形赋值 权限菜单
class MenuList extends Component {
    state = {
        menuList: [],
        roleList: []
    };

    onSelect = (selectedKeys, info) => {
    };
    onCheck = (checkedKeys, info) => {

        const menuList = info.checkedNodes.map((item) => {
            return item.props.value.menu_id;
        });
        this.props.onConfirm(checkedKeys, menuList);
    };

    render() {
        const loop = data => data.map((item, index) => {
            if (item.subList) {
                return <TreeNode title={item.menu_name} key={item.menu_key}
                                 value={item}>{loop(item.subList)}</TreeNode>;
            }
            if (item.menu_key) {
                return <TreeNode title={item.menu_name} key={item.menu_key} value={item} isLeaf={true}/>;
            }
            return <TreeNode title={item.menu_name} key={item.menu_key} value={item} isLeaf={true}/>;
        });
        return (
            <span>
                <Tree
                    checkable
                    onCheck={this.onCheck}
                    onSelect={this.onSelect}
                    checkedKeys={this.props.occurMenuList}
                >
                    {loop(this.props.menuList)}
                </Tree>
            </span>
        );
    }

    componentWillMount() {
    }
}

const PositionManages = Form.create()(PositionManage);

export default PositionManages;
